package com.senyin.servlet.staffInfo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.senyin.common.BaseResponse;
import com.senyin.entity.StaffInfo;
import com.senyin.service.StaffInfoService;
import com.senyin.service.impl.StaffInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import static com.senyin.constant.UserConstant.USER_LOGIN_STATE;

public class StaffShowAllServlet extends HttpServlet {
    private StaffInfoService staffInfoService = new StaffInfoServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        StaffInfo attribute = (StaffInfo) req.getSession().getAttribute(USER_LOGIN_STATE);
        BaseResponse<List<StaffInfo>> listBaseResponse = null;
        try {
            listBaseResponse = staffInfoService.showAll(attribute);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        ObjectMapper objectMapper = new ObjectMapper();
        HashMap<String, Object> staffInfos = new HashMap<>();
        try {
            staffInfos.put("code",listBaseResponse.getCode());
            staffInfos.put("msg",listBaseResponse.getMessage());
            staffInfos.put("count",listBaseResponse.getTotal());
            staffInfos.put("data",listBaseResponse.getData());
            resp.getWriter().write(objectMapper.writeValueAsString(staffInfos));
        } catch (Exception e) {
            staffInfos.put("code",-1);
            staffInfos.put("msg","error");
            staffInfos.put("count",0);
            resp.getWriter().write(objectMapper.writeValueAsString(staffInfos));
        }


    }
}
